package com.galaxy.device.api;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.galaxy.common.core.domain.R;
import com.galaxy.common.core.validate.AddGroup;
import com.galaxy.common.core.validate.EditGroup;
import com.galaxy.common.log.annotation.Log;
import com.galaxy.common.log.enums.BusinessType;
import com.galaxy.common.mybatis.core.page.PageQuery;
import com.galaxy.common.mybatis.core.page.TableDataInfo;
import com.galaxy.device.domain.CheckStock;
import com.galaxy.device.domain.bo.DeviceStockBo;
import com.galaxy.device.domain.bo.OrderBo;
import com.galaxy.device.domain.vo.DeviceStockVo;
import com.galaxy.device.domain.vo.ProductVo;
import com.galaxy.device.service.IDeviceStockService;
import com.influxdb.client.domain.Check;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.NotNull;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备库存管理
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/stock")
public class DeviceStockApiController {

    private final IDeviceStockService deviceStockService;
    private final RemoteProductService remoteProductService;

    /**
     * 查询设备库存列表
     */
    @Operation(summary = "查询设备库存列表")
    @GetMapping("/list")
    public TableDataInfo<DeviceStockVo> list(DeviceStockBo bo, PageQuery pageQuery) {
        TableDataInfo<DeviceStockVo> result = deviceStockService.queryPageList(bo, pageQuery);
        // 收集所有商品ID
        List<Long> productIds = result.getRows().stream()
            .map(DeviceStockVo::getProductId)
            .filter(id -> id != null)
            .distinct()
            .toList();

        if (!productIds.isEmpty()) {
            // 批量获取商品信息
            R<List<ProductVo>> productInfoList = remoteProductService.getBatchInfo(productIds);
            if (productInfoList.getData() != null) {
                // 创建商品ID到商品信息的映射
                Map<Long, ProductVo> productMap = productInfoList.getData().stream()
                    .collect(Collectors.toMap(ProductVo::getId, product -> product));

                // 设置商品信息
                result.getRows().forEach(stock -> {
                    if (stock.getProductId() != null) {
                        ProductVo product = productMap.get(stock.getProductId());
                        if (product != null) {
                            stock.setProductName(product.getName());
                            stock.setProductNo(product.getProductNo());
                        }
                    }
                });
            }
        }
        return result;
    }

    /**
     * 获取设备库存详细信息
     */
    @Operation(summary = "获取设备库存详细信息")
    @Parameter(name = "id", description = "库存ID", required = true)
    @GetMapping("/{id}")
    public R<DeviceStockVo> getInfo(@NotNull(message = "库存ID不能为空") @PathVariable Long id) {
        DeviceStockVo stock = deviceStockService.queryById(id);
        if (stock != null && stock.getProductId() != null) {
            R<List<ProductVo>> productInfo = remoteProductService.getBatchInfo(List.of(stock.getProductId()));
            if (productInfo.getData() != null && !productInfo.getData().isEmpty()) {
                ProductVo product = productInfo.getData().get(0);
                stock.setProductName(product.getName());
                stock.setProductNo(product.getProductNo());
            }
        }
        return R.ok(stock);
    }

    /**
     * 新增设备库存
     */
    @Operation(summary = "新增设备库存")
    @Log(title = "设备库存", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Boolean> add(@Validated(AddGroup.class) @RequestBody DeviceStockBo bo) {
        return R.ok(deviceStockService.insertByBo(bo));
    }

    /**
     * 修改设备库存
     */
    @Operation(summary = "修改设备库存")
    @Log(title = "设备库存", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Boolean> edit(@Validated(EditGroup.class) @RequestBody DeviceStockBo bo) {
        return R.ok(deviceStockService.updateByBo(bo));
    }

    /**
     * 删除设备库存
     */
    @Operation(summary = "删除设备库存")
    @Log(title = "设备库存", businessType = BusinessType.DELETE)
    @Parameter(name = "ids", description = "库存ID串", required = true)
    @DeleteMapping("/{ids}")
    public R<Boolean> remove(@NotNull(message = "库存ID不能为空") @PathVariable Long[] ids) {
        return R.ok(deviceStockService.deleteWithValidByIds(List.of(ids), true));
    }

    /**
     * 获取设备库存预警列表
     */
    @Operation(summary = "获取设备库存预警列表")
    @GetMapping("/alert")
    public TableDataInfo<DeviceStockVo> alertList(DeviceStockBo bo, PageQuery pageQuery) {
        return deviceStockService.queryAlertList(bo, pageQuery);
    }

    /**
     * 批量更新设备库存
     */
    @Operation(summary = "批量更新设备库存")
    @Log(title = "设备库存", businessType = BusinessType.UPDATE)
    @PutMapping("/batch")
    public R<Boolean> batchUpdate(@Validated(EditGroup.class) @RequestBody List<DeviceStockBo> boList) {
        return R.ok(deviceStockService.batchUpdate(boList));
    }

    /**
     * 查询有库存的设备
     */
    @GetMapping("getDevice/{productId}")
    public R<List<DeviceStockVo>> getDevice(@PathVariable Long productId) {
        return R.ok(deviceStockService.getDevice(productId));
    }



    @PostMapping("/checkStock")
    public R<Boolean> checkStock(@RequestBody CheckStockRequest request) {
        return R.ok(deviceStockService.checkStock(request.getCheckStockList(), request.getOrderBo()));
    }

    @Data
    public static class CheckStockRequest {
        private List<CheckStock> checkStockList;
        private OrderBo orderBo;
    }

    @PutMapping("/updateStock")
    public R<Boolean> updateStock(@RequestBody List<CheckStock>  checkStockList) {
        return R.ok(deviceStockService.updateStock(checkStockList));
    }

}
